<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <script>
     const arr = [
            {id:1,pid:'',name:'财务部'},
            {id:2,pid:1,name:'财务核算部'},
            {id:3,pid:2,name:'财务核算分部'},
            {id:4,pid:'',name:'人事部'},
            {id:5,pid:4,name:'杭州人事部'}
        ]
        function  fn(arr,pid) {
            const tempArr =[]
            arr.forEach(item =>{
                if(item.pid === pid){
                    tempArr.push(item)
                    item.children=fn (arr,item.pid)
                }
            })
            return tempArr
        }
          console.log(fn(depts,''));


        // const newArr =[]
        // arr.forEach(item =>{
        //     if(item.pid ===''){
        //         const tempArr =[]
        //         arr.forEach(item1 =>{
        //             if(item1.pid === item.id){
        //               tempArr.push(item1)
        //             }
        //         })
        //         if(tempArr.length >0){
        //             item.children = tempArr
        //         }
        //         newArr.push(item)
        //     }
        // })
        // console.log(newArr)
   </script>
</body>
</html>